
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
const jsdom = require("jsdom");
const {JSDOM} = jsdom;
var iconv = require('iconv-lite');
const fs = require("fs");

var content = fs.readFileSync('jquery_v1.12.4.js', {encoding:'binary'});
var jquery_str = iconv.decode(new Buffer.from(content, 'binary'), 'utf-8');

app.use(bodyParser.urlencoded({
    parameterLimit: 50000,
    limit: '50mb',
    extended: false
}));

// app.get('/', function (req, res) {
//     res.send('Hello World');
// })

var asyn_str = "<script>function setTimeout(a, b) {if(typeof(a) != 'undefined'){a();}} function setInterval(a, b) {if(typeof(a) != 'undefined'){a();}} </script>"


app.post('/api/jsdom_chanquan_beijing', function (req, res) {
    const resp = {};
    try {
        var html = req.body.html.toString();

        // 替换html
        html = html + jquery_str + " " + asyn_str;
        html = html.replace('$("#sellercondition").html(sellerhtml);', '$("#sellercondition").html("<table>" + sellerhtml + "</table>");')

        plugins = [];
        var options = {
            // referrer: "",
            userAgent: "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36",
            resources: "usable",    // 假如你想通过<script src="">来执行外部脚本，你需要确保已经加载了它们。为此，请添加选项resources:"usable"
            runScripts: "dangerously",
            url: 'http://www.cbex.com.cn/',
            // virtualConsole: new jsdom.VirtualConsole(),
            cookieJar: new jsdom.CookieJar(),
            pretendToBeVisual: true,
            beforeParse(window) {
                // window.document.addEventListener = (a, b, c) => {
                //     console.log('addEventListener a', a);
                //     console.log('addEventListener b', b);
                //     // return b()
                // };
                window.screen = {
                    width: 2560,
                    availHeight: 1400,
                    availLeft: 0,
                    availTop: 0,
                    availWidth: 2560,
                    colorDepth: 24,
                    height: 1440,
                    pixelDepth: 24,
                    orientation: {
                        angle: 0,
                        type: "landscape-primary"
                    }
                };
                window.getjs = () => {
                    return window.js
                };
                window.navigator.languages = ["zh-CN", "zh"];
                window.navigator.plugins = plugins;
                window.navigator.getBattery = () => {
                    return {
                        'charging': true,
                        'chargingTime': 0,
                        'dischargingTime': Infinity,
                        'level': 1,
                    }
                };
                window.navigator.mimeTypes = [{"type": "application/360softmgrplugin"}, {"type": "application/aliedit"}, {"type": "application/asx"}, {"type": "application/bd-npyunwebdetect-plugin"}, {"type": "application/cenroll.cenroll.version.1"}, {"type": "application/futuresplash"}, {"type": "application/futuresplash"}, {"type": "application/futuresplash"}, {"type": "application/futuresplash"}, {"type": "application/hwepass2001.installepass2001"}, {"type": "application/hwpta.itrushwpta"}, {"type": "application/hwwdkey.installwdkey"}, {"type": "application/itrusenroll.certenroll.version.1"}, {"type": "application/mozilla-npqihooquicklogin"}, {"type": "application/npalicdo"}, {"type": "application/npalissologin"}, {"type": "application/npqqwebgame"}, {"type": "application/nptxsso"}, {"type": "application/npxf-qqminidl"}, {"type": "application/npxluser_plugin"}, {"type": "application/pdf"}, {"type": "application/pta.itruspta.version.1"}, {"type": "application/qscall-plugin"}]
                window.navigator.connection = {
                    'downlink': 10,
                    'effectiveType': '4g',
                    'rtt': 50,
                    'saveData': false
                };
                window.Infinity = Infinity;
            },

        };
        const dom = (new JSDOM(html, options));
        const window = dom.window;

        window.addEventListener('load', function () {
            r_html = dom.window.document.documentElement.outerHTML;
            r_html = r_html.replace(jquery_str, '').replace(asyn_str, '');

             // 持有产（股）权比例 //拟转让产（股）权比例 //持有股份数 //拟转让股份数 //持有产（股）权比例
            r_html = r_html.replace("//持有产（股）权比例", "").replace("//拟转让产（股）权比例", "").replace('//持有股份数', '').replace('//拟转让股份数', '')
            // console.log(r_html);
            resp.html = new Buffer(r_html).toString('base64');
            resp.status = 1;
            res.send(JSON.stringify(resp));
        });
    } catch (err) {
        resp.status = 2;
        resp.message = err.message;
        res.send(JSON.stringify(resp));
    }
});

var server = app.listen(5592, function () {

    var host = server.address().address;
    var port = server.address().port;

    console.log("应用实例，访问地址为 http://%s:%s", host, port)
});